﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace SocketClient
{
    public static class SocketClientHelper
    {
        private static bool IsConnectionSuccessful = false;
        static ManualResetEvent TimeoutObject = new ManualResetEvent(false);

        /// <summary>
        /// Requests the is online.
        /// </summary>
        /// <param name="ip">The ip.</param>
        /// <param name="port">The port.</param>
        /// <returns></returns>
        public static bool RequestIsOnline( string ip, int port)
        {
            TcpClient tcpClient = new TcpClient();

            try
            {
                
                tcpClient.BeginConnect(ip, port, new AsyncCallback(ConnectedCallback), tcpClient);

                if (TimeoutObject.WaitOne(5000, false)) 
                {
                    return IsConnectionSuccessful;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                tcpClient.Close();
            }
        }

        /// <summary>
        /// Connects the specified ip.
        /// </summary>
        /// <param name="ip">The ip.</param>
        /// <param name="port">The port.</param>
        /// <returns></returns>
        public static TcpClient Connect(string ip, int port)
        {
            TcpClient tcpClient = new TcpClient();

            try
            {
                tcpClient.Connect(ip, port);
                return tcpClient;
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static void ConnectedCallback(IAsyncResult asyncronusResult)
        {
            try
            {
                IsConnectionSuccessful = false;
                TcpClient tcpclient = asyncronusResult.AsyncState as TcpClient;

                if (tcpclient.Client != null)
                {
                    tcpclient.EndConnect(asyncronusResult);
                    IsConnectionSuccessful = true;
                }
            }
            catch (Exception)
            {
                IsConnectionSuccessful = false;
            }
            finally
            {
                TimeoutObject.Set();
            }
        }
    }
}
